package com.captain.leetcode.中级.滑动窗口;

import java.util.HashMap;
import java.util.Map;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/1/10 16:53
 */
public class 无重复字符的最长子串3 {
    public static void main(String[] args) {
        System.out.println(new 无重复字符的最长子串3().lengthOfLongestSubstring("abcabcbb"));
    }

    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int max = 0;
        int left = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            //如果存在,两种情况, abca abba
            if (map.containsKey(s.charAt(i))) {
                left = Math.max(left, map.get(s.charAt(i)));
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i - left + 1);
        }
        return max;
    }
}
